import React, { memo, useEffect, useState } from "react";
import { Table, Space, Button, Drawer, Form,Input } from "antd";
import { getList, del, findOne,edit } from "../request/user";
const Home = memo(() => {
  const [list, setList] = useState([]);
  const [open, setOpen] = useState(false);
  const [values,setValues] = useState({})
  const [title,setTitle] = useState('')
  const [id,setID] = useState("")
  const onFinish =async (values)=>{
    await edit(id,values)
    initList()
    setOpen(false)
  }
  const onClose = () => {
    setOpen(false);
  };
  const initList = async () => {
    let res = await getList();
    console.log(res, "HOME");
    setList(res.data);
  };
  const columns = [
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={async () => {
              let res = await findOne(record._id);
              setTitle('查看')
              setValues(res)
              setOpen(true);
            }}
          >
            查看
          </Button>
          <Button
            type="primary"
            danger
            onClick={async () => {
              await del(record._id);
              initList();
            }}
          >
            删除
          </Button>
          <Button
            type="primary"
            danger
            onClick={ async ()=>{
              let res = await findOne(record._id);
              setValues(res)
              setID(record._id)
              setTitle('修改')
              setOpen(true)
            }}
          >
            修改
          </Button>
        </Space>
      ),
    },
  ];
  useEffect(() => {
    initList();
  }, []);
  return (
    <div>
      <Table dataSource={list} columns={columns} />;
      <Drawer title={title} placement="right" onClose={onClose} open={open}>
        <Form initialValues={values} onFinish={onFinish}>
          <Form.Item
            label="用户名"
            name="username"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
          >
            <Input />
          </Form.Item>
          <Button htmlType="submit">
            确认修改
          </Button>
        </Form>
      </Drawer>
    </div>
  );
});

export default Home;
